package com.szq.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.szq.yygh.hosp.model.hosp.Schedule;
import com.szq.yygh.hosp.repository.ScheduleRepository;
import com.szq.yygh.hosp.service.DepartmentService;
import com.szq.yygh.hosp.service.HospitalService;
import com.szq.yygh.hosp.service.ScheduleService;
import com.szq.yygh.hosp.vo.hosp.BookingScheduleRuleVo;
import com.szq.yygh.hosp.vo.hosp.ScheduleQueryVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * All rights Reserved, Designed By www.jx-lab.com
 * @Title: ScheduleServiceImpl
 * @Description:
 * @author lixy
 * @date 2021/8/19 18:25
 * @version V1.0
 * @Copyright: www.jx-lab.com Inc. All rights reserved.
 * 注意：本内容仅限于众合景轩信息技术有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;

    /**
     * 保存排班信息
     * @param requestMap
     */
    @Override
    public void saveSchedule(Map<String, Object> requestMap) {
        String jsonStr = JSONObject.toJSONString(requestMap);
        Schedule schedule = JSONObject.parseObject(jsonStr, Schedule.class);

        //根据医院编号和科室编号查询是否存在
        Schedule oldSchedule = scheduleRepository.findByHoscodeAndHosScheduleId
                (schedule.getHoscode(), schedule.getHosScheduleId());
        if (null != oldSchedule){
            schedule.setCreateTime(schedule.getCreateTime());
            schedule.setIsDeleted(0);
        }else{
            schedule.setCreateTime(new Date());
        }
        schedule.setStatus(1);
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }

    /**
     * 分页查询排班信息
     * @param page
     * @param limit
     * @param scheduleQueryVo
     * @return
     */
    @Override
    public Page<Schedule> selectPage(Integer page, Integer limit, ScheduleQueryVo scheduleQueryVo) {
        Pageable pageable = PageRequest.of(page-1, limit);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        Example<Schedule> example = Example.of(schedule, matcher);
        Page<Schedule> result = scheduleRepository.findAll(example, pageable);
        return result;
    }

    /**
     * 删除排班信息
     * @param hoscode
     * @param hosScheduleId
     */
    @Override
    public void removeSchedule(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.findByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (null != schedule){
            scheduleRepository.delete(schedule);
        }
    }

    /**
     * 查询排班规则数据
     * @param page
     * @param limit
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Map<String, Object> getScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        //1、根据医院编号和科室编码查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        //2、根据日期分组
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
                .first("workDate").as("workDate")
                        //3、统计号源数量
                .count().as("docCount")
                .sum("reservedNumber").as("reservedNumber")
                .sum("availableNumber").as("availableNumber"),
                Aggregation.sort(Sort.Direction.DESC, "workDate"),
                //4、分页
                Aggregation.skip((long)(page-1)*limit),
                Aggregation.limit(limit)
        );

        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleList = aggregate.getMappedResults();

        //分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalList = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalList.getMappedResults().size();

        bookingScheduleRuleList.stream().forEach(t->{
            String dayOfWeek = this.getDayOfWeek(new DateTime(t.getWorkDate()));
            t.setDayOfWeek(dayOfWeek);
        });

        //封装返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList", bookingScheduleRuleList);
        result.put("total", total);

        //获取医院信息
        String hosName = hospitalService.getHosName(hoscode);

        //其他数据
        Map<String, Object> baseMap = new HashMap<>();
        baseMap.put("hosname", hosName);
        result.put("baseMap", baseMap);
        return result;
    }

    /**
     * 查询排班详细信息
     * @param hoscode
     * @param depcode
     * @param workDate
     * @return
     */
    @Override
    public List<Schedule> getScheduleDetail(String hoscode, String depcode, String workDate) {
        List<Schedule> scheduleList = scheduleRepository.findByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate).toDate());
        //封装排班详情其他信息：医院名称，科室名称，日期对应星期
        scheduleList.stream().forEach(t->{
            this.packageSchedule(t);
        });
        return scheduleList;
    }

    private void packageSchedule(Schedule t) {
        //医院名称
        t.getParam().put("hosname", hospitalService.getHosName(t.getHoscode()));
        //科室名称
        t.getParam().put("deptname", departmentService.getDeptName(t.getHoscode(), t.getDepcode()));
        //日期对应星期
        t.getParam().put("dayOfWeek", this.getDayOfWeek(new DateTime(t.getWorkDate())));
    }


    /**
     * 根据日期获取周几数据
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }
}
